package com.zxq.large_link_app.http;


import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.zxq.large_link_app.enity.IotProject;
import com.zxq.large_link_app.enity.IotWrapperDTO;
import com.zxq.large_link_app.http.listen.ISwitchPlatformListener;
import com.zxq.large_link_app.sp.SpDBLite;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class HttpAddProject implements ISwitchPlatformListener {

    static HttpAddProject httpAddProject = new HttpAddProject();

    private HttpAddProject(){

    }
    /**
     * 获取项目的监听
     * @return
     */
    public static HttpAddProject getInstance() {

        return httpAddProject;
    }

    /**
     * 行为路径，不允许变动
     */
    final String saveProjectAction = "/iot/project/new";


    /**
     * 通知切换平台
     * @param url
     */
    @Override
    public void notifyPlatformSwitch(String url) {
        Log.e("url",url + "");
        if(url != null) {
            SpDBLite.getObj().saveBaseUrl(url);
        }
    }

    /**
     * 添加项目信息
     * @param iotProject
     * @return
     */
    public Boolean addProjectInfo(IotProject iotProject) {

        String result =  saveProjectInfo(iotProject);
        IotWrapperDTO<Boolean> iotWrapperDTO = JSON.parseObject(result, IotWrapperDTO.class);
        if(iotWrapperDTO.getData() == null) {
            return false;
        }
        return iotWrapperDTO.getData();
    }



    private String saveProjectInfo(IotProject iotProject) {
        OkHttpClient client = new OkHttpClient();
        //设置数据类型为JSON类型
        String url = SpDBLite.getObj().getWebJoint() + saveProjectAction;
        Log.e(getClass().getName(),url);
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        //JSON格式数据
        String jsonStr = JSON.toJSONString(iotProject);
        Log.e(getClass().getName(),jsonStr);
        RequestBody requestBody = RequestBody.create(mediaType, jsonStr);

        Request request = new Request.Builder()
                .post(requestBody)
                .url(url)
                .build();
        try {
            String responseData = client.newCall(request).execute().body().string();
            return responseData;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }










}
